﻿using System;
using System.Web;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Web.SessionState;
using System.Net.Mail;
using System.Web.Configuration;
using Newtonsoft.Json;
using Newtonsoft;
using PUCIT.eFCS.Business;
using PUCIT.eFCS.Utility.Encryption;
using System.Linq;

namespace PUCIT.eFCS
{
    /// <summary>
    /// Summary description for Controller
    /// </summary>
    public class Controller : IHttpHandler, IRequiresSessionState
    {

        public void ProcessRequest(HttpContext context)
        {
            if (context.Request.HttpMethod.Equals("post", StringComparison.OrdinalIgnoreCase))
            {
                if (context.Request.Files.Count > 0 && context.Request.Form.Count <= 0)
                {
                    List<Attachments> list = (List<Attachments>)context.Session["attachments"];
                    HttpFileCollection files = context.Request.Files;
                    foreach (string key in files)
                    {
                        HttpPostedFile file = files[key];
                        string fileName = file.FileName;

                        //BusinessClass efc = new BusinessClass();
                        //int logineduserId = Section.fId;
                        int logineduserId = (int)(context.Session["userId"]);
                        BusinessClass efcs = new BusinessClass();
                        efcs.createDirectory(logineduserId);
                        int i = logineduserId;
                        string mapPath = "~/Uploads/";
                        mapPath += logineduserId;
                        mapPath += "/";
                        fileName = context.Server.MapPath(mapPath + fileName);

                        Attachments a = new Attachments();
                        a.description = key;
                        a.Path = fileName;
                        //Section.attList.Add(a);
                        list.Add(a);

                        file.SaveAs(fileName);
                    }
                    context.Session["attachments"] = list;
                }
                // getting user profile data from user (student for now)
                else if (context.Request.Form.Count > 0)
                {
                    NameValueCollection formData = context.Request.Form;

                    string userName = formData["username"];
                    string fatherName = formData["father"];
                    string day = formData["day"];
                    string month = formData["month"];
                    string year = formData["year"];
                    string email = formData["email"];
                    string semester = formData["semester"];
                    string rollNo = formData["rollNo"];
                    string section = formData["section"];
                    string sessionFrom = formData["from"];
                    string sessionTo = formData["to"];

                    string dtb = month + "/" + day + "/" + year;
                    DateTime dob = Convert.ToDateTime(dtb);

                    string session = sessionFrom + "-" + sessionTo;

                    eFCS.Business.BusinessClass efcs = new BusinessClass();
                    efcs.SaveStudent(userName, fatherName, email, dob, semester, rollNo, section, session);
                    return;
                }


                ///////////////////////////////////////////////////////////////////////////
                context.Response.ContentType = "text/plain";
                context.Response.Write("File(s) uploaded successfully!");

            }

            else if (context.Request.HttpMethod.Equals("get", StringComparison.OrdinalIgnoreCase))
            {
                try
                {
                    if (context.Request.QueryString["action"].Equals("InitiateCirculation"))
                        InitiateCirculation(context);

                    else if (context.Request.QueryString["action"].Equals("ViewFormTemplate"))
                        ViewFormTemplate(context);

                    else if (context.Request.QueryString["action"].Equals("GetFormDetails"))
                        ViewCirculationDetails(context, Convert.ToInt32(context.Request.QueryString[1]));

                    else if (context.Request.QueryString["action"].Equals("EditCirculationDetails"))
                        EditCirculationDetails(context, Convert.ToInt32(context.Request.QueryString[1]));

                    else if (context.Request.QueryString["action"].Equals("GetFieldIdList"))
                        GetFieldIdList(context);

                    else if (context.Request.QueryString["action"].Equals("SaveSectionValues"))
                        SaveSectionValues(context);
                    else if (context.Request.QueryString["action"].Equals("GeneratePrintPreview"))
                        GeneratePrintPreview(context);
                    else if (context.Request.QueryString["action"].Equals("UserProfile"))
                        UserProfile(context);
                    else if (context.Request.QueryString["action"].Equals("loadProfileForm"))
                        loadProfileForm(context);
                    else if (context.Request.QueryString["action"].Equals("SaveUserProfile"))
                        SaveUserProfile(context);
                    else if (context.Request.QueryString["action"].Equals("SaveProfileSectionValues"))
                        SaveProfileSectionValues(context);
                    else if (context.Request.QueryString["action"].Equals("GetInitiatedForms"))
                        GetInitiatedForms(context);
                    else if (context.Request.QueryString["action"].Equals("GetDocumentsList"))
                        GetDocumentsList(context);
                    else if (context.Request.QueryString["action"].Equals("GetPageWrtRole"))
                        GetPageWrtRole(context);
                    else if (context.Request.QueryString["action"].Equals("GetLeftPanelContents"))
                        GetLeftPanelContents(context);
                    else if (context.Request.QueryString["action"].Equals("ViewCirculationList"))
                        ViewCirculationList(context);
                    else if (context.Request.QueryString["action"].Equals("StatusFilter"))
                        StatusFilter(context, context.Request.QueryString[1]);                    
                    else if (context.Request.QueryString["action"].Equals("FormTypeFilter"))
                        FormTypeFilter(context, context.Request.QueryString[1]);//ViewToDoList
                    else if (context.Request.QueryString["action"].Equals("ViewToDoList"))
                        ViewToDoList(context);//ViewCompleteCirculationSAC
                    else if (context.Request.QueryString["action"].Equals("ViewCompleteCirculationSAC"))
                        ViewCompleteCirculationSAC(context);
                    else if (context.Request.QueryString["action"].Equals("GetDocumentsListInInitiateCirculation"))
                        GetDocumentsListInInitiateCirculation(context);
                    else if (context.Request.QueryString["action"].Equals("GetRoleFromSession"))
                        GetRoleFromSession(context); 
                    
                    
                }
                catch (Exception)
                {
                }
            }

        }

        void UpdateFormTemplate(HttpContext context)
        {
            try
            {

            }
            catch (Exception)
            {
                context.Response.Write("<h1>Page not found!</h1>");
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }

        bool IsTextArea(string htmlId)
        {
            if (htmlId.EndsWith("Explanation") || htmlId.EndsWith("Comments"))
                return true;

            return false;
        }

        string GetCompleteTag(HttpContext context, string field_id, string tag, string value, bool isReadOnly, bool isTextArea, int logId)
        {
            ////// file attachment code
            if (tag == "<br/><a href=")
            {
                tag += value;
                return tag;
            }

            ////////////////


            string ch = "";
            if (isReadOnly)  // if sector 
                tag += " readonly=readonly style='background-color:LightGray'";


            if (isTextArea)
            {

                tag += ">";
                if (value != null)
                    tag += value;

                tag += "</textarea>";
                ch = tag;
            }
            else
            {
                //  value = "abc";
                if (Convert.ToString(tag.Substring(1, 3)) == "pro")//        "<profileattr=4>")
                {
                    int attrId = Convert.ToInt32(tag.Substring(13, 1));

                    int loginned_userId = logId;
                    BusinessClass eFCS = new BusinessClass();
                    //userprof u = new userprof();
                    string val = eFCS.getUserProfilevalues(attrId, loginned_userId);

                    //loading the profile object
                    value = val;
                    //tag = "<input type=text id=StdRollNo docname=StdRollNo size=59";// value = 1 />";
                    tag = "<input type=text ";
                    tag += (" id='" + field_id + "'");
                    tag += " size=59";
                    tag += (" value='" + value + "'");
                    tag += " readonly=readonly style='background-color:LightGray'";
                    tag += "/>";
                }
                //else if (Convert.ToString(tag.Substring(1, 3)) == "att")//        "<profileattr=4>")
                //{

                //}
                else
                {
                    if (value != null)
                    {
                        tag += (" value='" + value + "'");
                    }
                    tag += "/>";
                }
            }
            return tag;


        }

        void ProcessFieldHtmlTags(HttpContext context, Document document, int userId)
        {
            //document.docinit = 1;
            int logId = 0;
            foreach (Section section in document.DocumentSections)
            {
                bool secUserFound = true;
                if (userId == section.UserId)
                {
                    secUserFound = false;  //if section user found then he is able to eidt otherwise the field is just readonly
                    context.Session["sectionId"] = section.SectionId;
                    logId = (int)context.Session["userId"];
                }
                else
                {
                    logId = document.docinit;

                }

                ///////////////// file attachment code
                if (section.SectionTitle == "Attachments")
                {
                    section.SectionFields = new List<Field>();
                    foreach (Attachments item in section.attList)
                    {
                        Field f = new Field();
                        f.FieldHtml = "<br/><a href=";
                        f.FieldValue = "'" + item.Path + "'" + ">" + item.description + "</a>";
                        f.FieldHtmlId = "atch";

                        section.SectionFields.Add(f);
                    }
                    foreach (Field field in section.SectionFields)
                    {
                        field.FieldHtml = GetCompleteTag(context, field.FieldHtmlId, field.FieldHtml, field.FieldValue, secUserFound, false, logId);
                    }

                }
                /////////////////////////////////
                else
                {
                    foreach (Field field in section.SectionFields)
                    {
                        field.FieldHtml = GetCompleteTag(context, field.FieldHtmlId, field.FieldHtml, field.FieldValue, secUserFound, IsTextArea(field.FieldHtmlId), logId);
                    }
                }


                //foreach (Field attment in section.SectionAttachment)
                //{
                //    field.FieldHtml = <a href ....>desc</a>(context, field.FieldHtmlId, field.FieldHtml, field.FieldValue, secUserFound, IsTextArea(field.FieldHtmlId));
                //}

            }
        }

        void ProcessTemplateFieldHtmlTags(HttpContext context, Document document)
        {
            foreach (Section section in document.DocumentSections)
            {
                foreach (Field field in section.SectionFields)
                {
                    if (field.FieldHtmlId.Equals("StdSemesterDDL"))
                    {
                        field.FieldHtml = "<select id=StdSemesterDDL name=StdSemesterDDL><option value=1st>1st</option><option value=2nd>2nd</option><option value=3rd>3rd</option><option value=4th>4th</option><option value=5th>5th</option><option value=6th>6th</option><option value=7th>7th</option><option value=8th>8th</option></select>";
                    }

                    if (field.FieldHtmlId.EndsWith("DDL")) // Drop Down List
                    {
                        field.FieldHtml = "<select disabled='disabled' " + field.FieldHtml.Substring(8);
                    }
                    else if (field.FieldHtmlId.EndsWith("RB")) // Radio Button
                    {
                        string[] htmlParts = field.FieldHtml.Split('/');
                        htmlParts[0] += "disabled='disabled'";
                        htmlParts[1] += "disabled='disabled'";

                        field.FieldHtml = htmlParts[0] + "/" + htmlParts[1] + "/" + htmlParts[2];
                    }
                    else
                    {
                        field.FieldHtml = GetCompleteTag(context, field.FieldHtmlId, field.FieldHtml, field.FieldValue, true, IsTextArea(field.FieldHtmlId), 0);
                    }
                }
            }
        }

        string GenerateCirculationForm(Document document)
        {
            //Solution is that we don't solve it through ajax.

            //here we'll make html of "Edit Section" and "save as it is" Buttons.
            //here we have to store each section's html in unique DIV.
            string formHtml = "<h2>" + document.DocumentName + "</h2>";

            int i = 1;
            foreach (Section section in document.DocumentSections)
            {
                formHtml += ("<h3><u>" + section.SectionTitle + "</u></h3>");
                //Each Section within a separate Div, when edit button of that div is pressed, make CK-Editor visible, use .innerHtml property of this div to generate the form
                //if Save button of that div is pressed, then get innerHTML, parse it and save it with new document id.

                formHtml += ("<div id='" + i + "'>");
                formHtml += "<table cellpadding=8>";
                foreach (Field field in section.SectionFields)
                {
                    if (field.FieldHtml.IndexOf("type='file'") > 0)
                    {
                        // need to put document name in link
                        formHtml += ("<tr><td> " + field.FieldLabel + "<a>" + field.FieldHtml + "</a></td></tr>");
                    }
                    else
                    {
                        formHtml += ("<tr><td>" + field.FieldLabel + "</td><td>" + field.FieldHtml + "</td></tr>");
                    }
                }

                formHtml += "</table>";
                formHtml += "</div>";
                //formHtml += 
                i++;

            }

            formHtml += GetFileAttachment();
            return formHtml;
        }

        string GeneratePrintForm(Document document)
        {
            string formHtml = "<h2>" + document.DocumentName + "</h2>";


            foreach (Section section in document.DocumentSections)
            {
                formHtml += ("<h3><u>" + section.SectionTitle + "</u></h3>");
                formHtml += "<table cellpadding=8>";
                foreach (Field field in section.SectionFields)
                {
                    formHtml += ("<tr><td>" + field.FieldLabel + "</td><td>" + field.FieldValue + "</td></tr>");
                }
                formHtml += "</table>";
            }
            return formHtml;
        }

        void SendEmailNotification(Circulation circulation)
        {
            try
            {
                MailMessage msg = new MailMessage();
                BusinessClass eFCS = new BusinessClass();
                NameValueCollection queryStringParameters = new NameValueCollection();
                int userId = eFCS.GetUserIdByUserName(circulation.CurrentStation);

                string toEmailAddress = eFCS.GetEmailByUserId(userId);
                //string toEmailAddress = "efcssac@gmail.com";

                msg.To.Add(toEmailAddress);
                msg.From = new MailAddress("esdprjct@gmail.com");
                msg.Subject = "eFCS Circulation " + circulation.CirculationId + " | " + circulation.CurrentStation;

                msg.IsBodyHtml = true;

                string body = "<html><body>";
                body += "<h2>Circulation Details</h2><table rules=all cellpadding=10><tr style='text-align:center'><th>Circulation Id</th><th>Form Type</th><th>Initiater</th><th>Submission Date</th><th>Submission Time</th><th>Progress</th><th>Current Station</th></tr>";
                body += ("<tr style='text-align:center'><td>" + circulation.CirculationId + "</td><td>" + eFCS.GetAbbreviation(circulation.Document.DocumentName) + "</td><td>" + circulation.Initiater + "</td><td>" + circulation.SubmissionDate.ToShortDateString() + "</td><td>" + circulation.SubmissionDate.ToShortTimeString() + "</td><td>" + circulation.Progress + "%</td><td>" + circulation.CurrentStation + "</td></tr></table>");

                body += GenerateCirculationForm(circulation.Document);

                /////// file attachments
                //List<Attachments> attList = eFCS.getAttachments(circulation.CirculationId);
                //if (attList.Count != 0)
                //{
                //    body += "<br/><br/><h2> Attachments</h2>";
                //    foreach (Attachments item in attList)
                //    {
                //        body += "<br/><a href = " + item.Path + ">" + item.description + "</a>";
                //    }
                //}
                ///////////


                queryStringParameters.Add("circulationId", circulation.CirculationId.ToString());
                queryStringParameters.Add("userId", userId.ToString());

                // Encrypt query string parameters
                string encryptedString = CryptoQueryStringHandler.EncryptQueryStrings(queryStringParameters, WebConfigurationManager.AppSettings["CryptoKey"]);

                if (circulation.Progress.Equals("100"))
                {
                    body += "<br /><h3>Click <a href='~/ViewCirculationDetails.aspx?" + encryptedString + "'>Here</a> to Open</h3>";
                }
                else
                {
                    body += "<br /><h3>Click <a href='~/EditCirculationDetails.aspx?" + encryptedString + "'>Here</a> to Open</h3>";
                }

                body += "</body></html>";

                msg.Body = body;
                //PUCIT
                SmtpClient smtpClient = new SmtpClient("172.16.0.4");

                //Home
                //SmtpClient smtpClient = new SmtpClient("smtp.gmail.com", 587);
                ////smtpClient.Host = "smtp.gmail.com";
                //smtpClient.EnableSsl = true;
                //smtpClient.UseDefaultCredentials = false;
                //smtpClient.Credentials = new System.Net.NetworkCredential("esdprjct", "esd12345");



                // PUCIT
                //smtpClient.Host = "192.168.1.4";
                //smtpClient.Port = 587;



                smtpClient.Send(msg);
            }
            catch (Exception exc)
            {
                String error = exc.ToString();
            }
        }

        void ViewFormTemplate(HttpContext context)
        {
            try
            {
                context.Response.ContentType = "text/plain";

                string encryptedQueryStringPrameters = (string)context.Session["params"];

                context.Session.Remove("params");

                // Decrypt query strings parameters
                string cryptoKey = WebConfigurationManager.AppSettings["CryptoKey"];
                string decryptedQueryString = CryptoQueryStringHandler.DecryptQueryStrings(encryptedQueryStringPrameters, cryptoKey);

                string[] keyValuePair = decryptedQueryString.Split('='); // e.g. {documentId,15

                int documentId = int.Parse(keyValuePair[1]);

                BusinessClass eFCS = new BusinessClass();

                Document document = eFCS.GenerateFormTemplate(documentId);

                ProcessTemplateFieldHtmlTags(context, document);

                string response = GenerateCirculationForm(document);

                context.Response.Write(response);
            }
            catch (Exception)
            {
                context.Response.Write("<h1>Page not found!</h1>");
            }
        }

        void InitiateCirculation(HttpContext context)
        {
            try
            {
                context.Session["currentSec"] = 0;
                context.Response.ContentType = "text/plain";

                BusinessClass eFCS = new BusinessClass();
                int documentId = int.Parse(context.Request.QueryString["documentId"]);

                context.Session["documentId"] = documentId;

                Document document = eFCS.GenerateForm(documentId, -1, (int)context.Session["categoryId"]);
                ProcessFieldHtmlTags(context, document, (int)context.Session["categoryId"]);
                string response = GenerateCirculationForm(document);

                int i = (int)context.Session["currentSec"];

                Section sec = new Section();
                sec.SectionId = (int)context.Session["sectionId"];
                context.Session["current_sec"] = sec;

                //response += GetFileAttachment();

                //here upload code
                response += "<br /><input id='Button1' style='margin-left:20px;' type='button' value='Submit' onclick='SaveSectionValues()'/>";
                context.Response.Write(response);
            }

            catch (Exception)
            {
            }
        }


        //loading the profile form
        void loadProfileForm(HttpContext context)
        {
            BusinessClass bc = new BusinessClass();

            try
            {
                string response = bc.GetUserProfileFormHtml();
                response += "<br /><input id='Button1' style='margin-left:20px;' type='button' value='Submit' onclick='SaveUserProfile()'/>";
                context.Response.Write(response);
            }
            catch (Exception)
            {
            }
        }

        void ViewCirculationDetails(HttpContext context, int cId)
        {
            try
            {
                context.Response.ContentType = "text/plain";

                int circulationId = cId;

                BusinessClass eFCS = new BusinessClass();

                Circulation circulation = eFCS.GetCirculationDetails(circulationId, true, -1);

                int userID =  Convert.ToInt32(context.Session["userId"]);
                circulation.Document.docinit = userID;

                ProcessFieldHtmlTags(context, circulation.Document, -1);

                string response = "<h2>Circulation Details</h2><table rules=all cellpadding=10><tr style='text-align:center'><th>Circulation Id</th><th>Form Type</th><th>Initiater</th><th>Submission Date</th><th>Submission Time</th><th>Progress</th><th>Current Station</th></tr>";

                response += ("<tr style='text-align:center'><td>" + circulation.CirculationId + "</td><td>" + eFCS.GetAbbreviation(circulation.Document.DocumentName) + " " + circulation.Document.DocumentVersion + "</td><td>" + circulation.Initiater + "</td><td>" + circulation.SubmissionDate.ToShortDateString() + "</td><td>" + circulation.SubmissionDate.ToLongTimeString() + "</td><td>" + circulation.Progress + "%</td><td>" + circulation.CurrentStation + "</td></tr></table>");
                response += "<br />";
                response += GenerateCirculationForm(circulation.Document);
                response += "<br />";
                response += "<br /><input id=" + circulation.CirculationId + " type='button' value='Print' onclick='javascript:getPrint(this.id)'/>";
                context.Response.Write(response);
            }
            catch (Exception)
            {
                context.Response.Write("<h1>Page not found!</h1>");
            }
        }

        void GeneratePrintPreview(HttpContext context)
        {
            try
            {
                context.Response.ContentType = "text/plain";

                BusinessClass eFCS = new BusinessClass();

                int circulationId = int.Parse(context.Request.QueryString["circulationId"]);

                Circulation circulation = eFCS.GetPrintPreview(circulationId);

                //ProcessFieldHtmlTags(context, circulation.Document, -1);

                string response = GeneratePrintForm(circulation.Document);
                response += "<br />";
                response += "<input type='button' value='Print' onclick='location.reload(true);window.print();'>";
                context.Response.Write(response);
            }
            catch (Exception)
            {
            }
        }

        void EditCirculationDetails(HttpContext context, int cId)
        {
            try
            {
                context.Response.ContentType = "text/plain";

                // as when user logged in, his session was set there, and only that logged in user can edit the data, so right
                // userId would be picked up.
                int userId = (int)context.Session["userId"];
                string response = "";
                
                BusinessClass eFCS = new BusinessClass();

                int circulationId = cId;

                Circulation circulation = eFCS.GetCirculationDetails(circulationId, true, userId);

                int catId = (int)context.Session["categoryId"];
                string username = eFCS.GetCategoryName(catId);
                // username = username.ToLower();

                circulation.Document.docinit = 1;
                if (circulation.CurrentStation.Equals(username))
                {

                    ProcessFieldHtmlTags(context, circulation.Document, userId);
                    context.Session["circulationId"] = circulationId;
                    context.Session["documentId"] = eFCS.GetCirculationDocumentId(circulationId);

                    response += "<h2>Circulation Details</h2><table rules=all cellpadding=10><tr style='text-align:center'><th>Circulation Id</th><th>Form Type</th><th>Initiater</th><th>Submission Date</th><th>Submission Time</th><th>Progress</th><th>Current Station</th></tr>";

                    response += ("<tr style='text-align:center'><td>" + circulation.CirculationId + "</td><td>" + eFCS.GetAbbreviation(circulation.Document.DocumentName) + " " + circulation.Document.DocumentVersion + "</td><td>" + circulation.Initiater + "</td><td>" + circulation.SubmissionDate.ToShortDateString() + "</td><td>" + circulation.SubmissionDate.ToLongTimeString() + "</td><td>" + circulation.Progress + "%</td><td>" + circulation.CurrentStation + "</td></tr></table>");

                    response += GenerateCirculationForm(circulation.Document);

                    response += "<br /><input id='Button1' type='button' value='Submit' onclick='SaveSectionValues()'/>";
                }
                else
                {
                    NameValueCollection queryStringParameters = new NameValueCollection();

                    queryStringParameters.Add("circulationId", circulation.CirculationId.ToString());

                    // Encrypt query string parameters
                    string encryptedString = CryptoQueryStringHandler.EncryptQueryStrings(queryStringParameters, WebConfigurationManager.AppSettings["CryptoKey"]);
                    string base_url = WebConfigurationManager.AppSettings["base_url"];

                    response += "<h1>You have already edited details of <a href='~/ViewStationUserCirculationDetails.aspx?" + encryptedString + "'>Circulation: " + circulation.CirculationId + "</a></h1>";
                }

                context.Response.Write(response);
            }
            catch (Exception)
            {
                context.Response.Write("<h1>Page not found!</h1>");
            }
        }

        //saving user profile fields
        void SaveUserProfile(HttpContext context)
        {
            try
            {
                context.Response.ContentType = "text/plain";

                BusinessClass eFCS = new BusinessClass();
                List<string> fieldHtmlIdList = eFCS.GetFieldHtmlIdListOfProfileAttr();

                string response = JsonConvert.SerializeObject(fieldHtmlIdList);
                context.Response.Write(response);
            }
            catch (Exception)
            {
            }
        }

        void GetFieldIdList(HttpContext context)
        {
            try
            {
                context.Response.ContentType = "text/plain";

                BusinessClass eFCS = new BusinessClass();
                List<string> fieldHtmlIdList = eFCS.GetFieldHtmlIdList((int)context.Session["sectionId"]);

                string response = JsonConvert.SerializeObject(fieldHtmlIdList);
                context.Response.Write(response);
            }
            catch (Exception)
            {
            }
        }

        void SaveSectionValues(HttpContext context)
        {

            try
            {
                List<string> fieldValues = new List<string>();
                Circulation circulationDetails;

                fieldValues = JsonConvert.DeserializeObject<List<string>>(context.Request.QueryString["jsonText"]);

                BusinessClass eFCS = new BusinessClass();

                if (context.Session["params"] != null)
                    context.Session.Remove("params");


                //if (context.Session.Count == 5 || context.Session.Count == 8) // documentId, sectionId, userId, username, categoryId, sec object

                if (context.Session.Count == 13)
                {
                    /*  HttpFileCollection Files;


                      Files = context.Request.Files; 

                      HttpPostedFile f = context.Request.Files["datasize"];
                      int length = f.ContentLength;
                      string name = f.FileName; 
                      */


                    /*   foreach (HttpPostedFile f in context.Request.Files)
                       {*/
                    //   f.SaveAs("~\\Attachments\\"+f.FileName);
                    /*} */


                    int circulationId = eFCS.SaveSectionValues((int)(context.Session["documentId"]), (int)(context.Session["sectionId"]), (int)(context.Session["userId"]), fieldValues); //here first was context of userId istaed of category id
                    Section att = new Section();
                    att.attList = (List<Attachments>)context.Session["attachments"];
                    att.SectionId = (int)(context.Session["sectionId"]);


                    eFCS.saveAttachments(att, circulationId);
                    //now here after getting form id save attachemnt in table
                    //BusinessClass b = new BusinessClass();
                    //b.saveAttachmentInfo((Section)context.Session["current_sec"] , circulationId);

                    circulationDetails = eFCS.GetCirculationDetails(circulationId, true, -1);
                    ProcessFieldHtmlTags(context, circulationDetails.Document, -1);

                    SendEmailNotification(circulationDetails);

                    context.Response.ContentType = "text/plain";

                    context.Session.Remove("documentId");
                    context.Session.Remove("sectionId");

                    NameValueCollection queryStringParameters = new NameValueCollection();

                    queryStringParameters.Add("circulationId", circulationId.ToString());

                    // Encrypt query string parameters
                    string encryptedString = CryptoQueryStringHandler.EncryptQueryStrings(queryStringParameters, WebConfigurationManager.AppSettings["CryptoKey"]);

                    // context.Response.Write("<h1>Successfully Saved!</h1><h1>Your Circulation Id is: <a href='ViewCirculationDetails.aspx?" + encryptedString + "'>" + circulationId + "</a></h1>");
                    context.Response.Write("<h1>Successfully Saved!</h1><h1>Your Circulation Id is: <a href='#' onclick='loadViewCirculationDetails(" + circulationId + "); return false'>" + circulationId + "</a> </h1>");

                }

                else // (Count = 6) i.e. circulationId, documentId, sectionId, userId, username (Save section values of a station user)
                {
                    int circulationId = (int)(context.Session["circulationId"]);

                    eFCS.SaveStationUserSectionValues(circulationId, (int)(context.Session["documentId"]), (int)(context.Session["sectionId"]), (int)(context.Session["userId"]), fieldValues);

                    circulationDetails = eFCS.GetCirculationDetails(circulationId, true, -1);
                    ProcessFieldHtmlTags(context, circulationDetails.Document, -1);

                    //SendEmailNotification(circulationDetails);

                    context.Response.ContentType = "text/plain";

                    context.Session.Remove("circulationId");
                    context.Session.Remove("documentId");
                    context.Session.Remove("sectionId");

                    context.Response.Write("<h1>Successfully Saved!</h1>");
                }
            }
            catch (Exception)
            {
            }
        }

        //saving profile values in table
        void SaveProfileSectionValues(HttpContext context)
        {
            BusinessClass bc = new BusinessClass();

            try
            {
                List<string> fieldValues = new List<string>();
                List<string> fieldIdValues = new List<string>();
                List<int> profileattrid = new List<int>();
                fieldValues = JsonConvert.DeserializeObject<List<string>>(context.Request.QueryString["jsonText"]);
                fieldIdValues = JsonConvert.DeserializeObject<List<string>>(context.Request.QueryString["jsonText2"]);

                //getting user id from email
                string email = Convert.ToString(context.Session["email"]);

                //getting username 
                string username = fieldValues[0];

                //here first saving user to users table  then getting the user id
                int userId = bc.AddStudent(username, email);

                //getting ids of fieldIdvalues means profile attribute id
                profileattrid = bc.getProfileattrId(fieldIdValues);

                //saving data to usr profile table
                bc.saveUserProfile(userId, fieldValues, profileattrid);


                //user id ====> from this email
                //profile id ==== > from the id list in javascript
                //profile value ===? this field value list
                //then chck after login again from bsef09m053
                //then circulation id problem
                //check other section for session 13 like if working for sac
                //after succesul regsteration ===> completing the sessions
                context.Response.Write("<h1>Successfully Registered<h1><br/><br/><a href='ViewCirculationList.aspx'>Go to Homepage</a>");
            }
            catch (Exception)
            {
            }
        }


        public string GetFileAttachment()
        {
            string response = "<br/>";

            response += "<div id='condiv' style='height:auto;border:0px solid blue;width:100%;border:1px dotted grey'>";
            response += "<a href='javascript:void(0)' id='mybutton' onClick='OpenFileUpload()'>Browse file OR Drop files here</a>";
            response += "<input type='file' name='filesToUpload[]' id='myfile' style='visibility:hidden;'  multiple='multiple' onchange='load_lst()' >";
            response += "<div id='dropbox'><span id='droplabel'>Drop file here...</span></div>";

            response += "<div id='abc' style='display:none'>";
            response += "<ul id='list_files'></ul>";
            response += "</div>";

            response += "</div>";

            return response;
        }

        public void UserProfile(HttpContext context)
        {
            context.Response.Write("in userprofile function");
        }

        public void GetInitiatedForms(HttpContext context)
        {
            BusinessClass bc = new BusinessClass();
            List<string> l = new List<string>();
            string response = "<select>";
            try
            {
                l = bc.GetUserForms(1);
                for (int i = 0; i < l.Count; i++)
                {
                    response += "<option>";
                    response += l[i];
                    response += "</option>";
                }
                response += "</select>";
                context.Response.Write(response);
            }
            catch (Exception)
            {
            }

        }
        public void GetDocumentsList(HttpContext context)
        {
            BusinessClass bc = new BusinessClass();
            List<Document> l = new List<Document>();
            try
            {
                BusinessClass eFCS = new BusinessClass();
                List<DocumentItem> documents = eFCS.GetDocumentList();

                int documentId = 0;

                string response = "";// "<select id='selectedForm'>";

                foreach (DocumentItem form in documents)
                {
                    documentId = eFCS.GetDocumentId(form.DocumentName, form.DocumentVersion);
                    response += "<option>" + form.DocumentName + "</option>";
                }

                //response += " </select>";

                // DropDownListContents.InnerHtml = innerHtml;
                // Request.ContentType = "multipart/form-data";
                context.Response.Write(response);
            }
            catch (Exception)
            {
            }
        }

        public void GetPageWrtRole(HttpContext context)
        {
            string role = Convert.ToString(context.Session["role"]);
            string response = "";
            if (role == "student")
            {
                response += "ViewCirculationList.aspx";
            }
            else if (role == "stationUser")
            {
                response += "ViewToDoList.aspx";
            }
            else if (role == "admin")
            {
                // response += "ViewCirculationList.aspx";
            }
            else if (role == "NewStudent")
            {
                 response += "UserProfile.aspx";
            }
            context.Response.Write(response);
        }

        public void GetLeftPanelContents(HttpContext context)
        {
            string role = Convert.ToString(context.Session["role"]);
            string response = "";
            string name = Convert.ToString(context.Session["username"]);
            if (role == "student")
            {
                response += "<h1>Welcome<h1>";
                response += "<h3>" + name + "</h3>";
                response += "<a href='http://accounts.google.com/logout'>Logout</a>" + "<br/><hr>";
                response += "<a href='#' onclick='loadViewCirculationList(); return false'>Home</a><br/>";
                response += "<a href='#' onclick='loadFormTypePages(); return false'>Initiate Circulation</a><br/>";
                response += "<a href='#' onclick='ShowReports(); return false'>View Reports</a><br/>";
            }
            else if (role == "stationUser")
            {
                response += "<h1>Welcome<h1>";
                response += "<h3>" + name + "</h3>";
                response += "<a href='http://accounts.google.com/logout'>Logout</a>" + "<br/><hr>";
                response += "<a href='#' onclick='loadViewCirculationList(); return false'>Home</a><br/>";
                response += "<a href='#' onclick='CompletedCirculations(); return false'>Completed Circulations</a><br/>";                
            }
            else if (role == "admin")
            {
                response += "<h2>Welcome " + name + "! </h2><br/>";
                response += "<a href='http://accounts.google.com/logout'>Logout</a>" + "<br/><hr>";
                response += "<a href='#' onclick='loadEditCirculationDetails(); return false'>Home</a><br/>";
                response += "<a href='#' onclick='loadCompletedCirculations(); return false'>Completed Circulations</a><br/>";

            }
            else if (role == "NewStudent")
            {
                response += "<h2>Welcome To Electronic Form Circulation System</h2>";
            }
            context.Response.Write(response);
        }

        void ViewCirculationList(HttpContext context, string status = null, string type = null)
        {
            BusinessClass eFCS = new BusinessClass();

            int uId = Convert.ToInt32(context.Session["userId"]);

            //get form lisst by user id             
            List<Form> forms = eFCS.GetFormsByUserId(uId);
            string formName = null;
            string abr = null;
            string response = "";

            if (status == null && type == null)
            {
                foreach (Form form in forms)
                {
                    formName = null;
                    abr = null;
                    formName = eFCS.GetDocumentNameByDocumentId(form.DocId);
                    abr = eFCS.GetAbbreviation(formName);

                    response += "<tr> <td style='width:16%;'> " + form.FormId + " </td>";
                    response += "<td style='width:16%;'> " + abr + " </td>";
                    response += "<td style='width:16%;'> " + form.subDate.Date + " </td>";
                    response += "<td style='width:16%;'> " + form.subDate.TimeOfDay + " </td>";
                    response += "<td style='width:16%;text-align:center'> " + form.progress + "%" + " </td>";
                    response += "<td style='width:16%;'><a href='#' onclick='loadViewCirculationDetails(" + form.FormId + "); return false'> " + "View Details" + "</a> </td></tr>";
                }
            }             
            
            context.Response.Write(response);
        }

        //filter forms by status
        void StatusFilter(HttpContext context, string status)
        {
            BusinessClass eFCS = new BusinessClass();

            int uId = Convert.ToInt32(context.Session["userId"]);

            //get form lisst by user id             
            List<Form> forms = eFCS.GetFormsByUserId(uId);
            string formName = null;
            string abr = null;
            string response = "";

            // status filter
            if (status != null)
            {
                if (status == "Complete")
                {
                    foreach (Form form in forms)
                    {
                        if (form.progress == "100")
                        {
                            formName = null;
                            abr = null;
                            formName = eFCS.GetDocumentNameByDocumentId(form.DocId);
                            abr = eFCS.GetAbbreviation(formName);

                            response += "<tr> <td> " + form.FormId + " </td>";
                            response += "<td> " + abr + " </td>";
                            response += "<td> " + form.subDate.Date + " </td>";
                            response += "<td> " + form.subDate.TimeOfDay + " </td>";
                            response += "<td> " + form.progress + "%" + " </td>";
                            response += "<td><a href='#' onclick='loadViewCirculationDetails(" + form.FormId + "); return false'> " + "View Details" + "</a> </td></tr>";
                        }
                    } 
                }
                else if (status == "Incomplete")
                {
                    foreach (Form form in forms)
                    {
                        if (form.progress != "100")
                        {
                            formName = null;
                            abr = null;
                            formName = eFCS.GetDocumentNameByDocumentId(form.DocId);
                            abr = eFCS.GetAbbreviation(formName);

                            response += "<tr> <td> " + form.FormId + " </td>";
                            response += "<td> " + abr + " </td>";
                            response += "<td> " + form.subDate.Date + " </td>";
                            response += "<td> " + form.subDate.TimeOfDay + " </td>";
                            response += "<td> " + form.progress + "%" + " </td>";
                            response += "<td><a href='#' onclick='loadViewCirculationDetails(" + form.FormId + "); return false'> " + "View Details" + "</a> </td></tr>";
                        }
                    }
                }
                else if (status == "All")
                {
                    foreach (Form form in forms)
                    {
                        formName = null;
                        abr = null;
                        formName = eFCS.GetDocumentNameByDocumentId(form.DocId);
                        abr = eFCS.GetAbbreviation(formName);

                        response += "<tr> <td> " + form.FormId + " </td>";
                        response += "<td> " + abr + " </td>";
                        response += "<td> " + form.subDate.Date + " </td>";
                        response += "<td> " + form.subDate.TimeOfDay + " </td>";
                        response += "<td> " + form.progress + "%" + " </td>";
                        response += "<td><a href='#' onclick='loadViewCirculationDetails(" + form.FormId + "); return false'> " + "View Details" + "</a> </td></tr>";                     
                    }
                }
            }
            context.Response.Write(response);
        }

        //form type filter
        void FormTypeFilter(HttpContext context, string type)
        {
            BusinessClass eFCS = new BusinessClass();

            int uId = Convert.ToInt32(context.Session["userId"]);

            //get form lisst by user id             
            List<Form> forms = eFCS.GetFormsByUserId(uId);
            string formName = null;
            string abr = null;
            string response = "";

            // form type filter
            if (type != null)
            {
                string type_abr = eFCS.GetAbbreviation(type);
                    foreach (Form form in forms)
                    {
                        formName = null;
                        abr = null;
                        formName = eFCS.GetDocumentNameByDocumentId(form.DocId);
                        abr = eFCS.GetAbbreviation(formName);

                        if (type_abr == abr)
                        {
                            response += "<tr> <td> " + form.FormId + " </td>";
                            response += "<td> " + abr + " </td>";
                            response += "<td> " + form.subDate.Date + " </td>";
                            response += "<td> " + form.subDate.TimeOfDay + " </td>";
                            response += "<td> " + form.progress + "%" + " </td>";
                            response += "<td><a href='#' onclick='loadViewCirculationDetails(" + form.FormId + "); return false'> " + "View Details" + "</a> </td></tr>";
                        }
                    }
             }

            string val = response;

             context.Response.Write(response);
        }

        //////////////////////////////////////////////////////////////////////////////////////
                
          //                              SAC SECTION        

        //////////////////////////////////////////////////////////////////////////////////////

        void ViewToDoList(HttpContext context)
        {
            BusinessClass eFCS = new BusinessClass();
           // List<string> forms = eFCS.GetUserForms((int)context.Session["categoryId"]);
           // string[] details;
            string response = "";

            List<CirculationItem> list = eFCS.GetToDoList((int)context.Session["categoryId"], 1, 1);

            /*<th>Circulation Id</th>
                <th>Form Type</th>
                <th>Initiater</th>
                <th>Submission Date</th>
                <th>Submission Time</th>
                <th>Progress</th>                
                <th>Edit Details</th>*/

            foreach(CirculationItem item in list)
            {
                if(item.Progress != "100%")
                {
                    response += "<tr> <td> " + item.CirculationId + " </td>";
                    response += "<td> " + item.FormType + " </td>";
                    response += "<td> " + item.Initiater + " </td>";
                    response += "<td> " + item.SubmissionDate + " </td>";
                    response += "<td> " + item.SubmissionTime + " </td>";
                    response += "<td> " + item.Progress + " </td>";
                    response += "<td><a href='#' onclick='EditCirculationDetails(" + item.CirculationId + "); return false'> " + "Edit Details" + "</a> </td></tr>";
                }
            }

            context.Response.Write(response);
        }

        void ViewCompleteCirculationSAC(HttpContext context)
        {
            BusinessClass eFCS = new BusinessClass();            
            string response = "";

            List<CirculationItem> list = eFCS.GetToDoList((int)context.Session["categoryId"], 1, 1);

            foreach (CirculationItem item in list)
            {
                if (item.Progress == "100%")
                {
                    response += "<tr> <td> " + item.CirculationId + " </td>";
                    response += "<td> " + item.FormType + " </td>";
                    response += "<td> " + item.Initiater + " </td>";
                    response += "<td> " + item.SubmissionDate + " </td>";
                    response += "<td> " + item.SubmissionTime + " </td>";
                    response += "<td> " + item.Progress + " </td>";
                    response += "<td><a href='#' onclick='EditCirculationDetails(" + item.CirculationId + "); return false'> " + "Edit Details" + "</a> </td></tr>";
                }
            }
            context.Response.Write(response);
        }

        public void GetDocumentsListInInitiateCirculation(HttpContext context)
        {
            BusinessClass bc = new BusinessClass();
            List<Document> l = new List<Document>();
            try
            {
                BusinessClass eFCS = new BusinessClass();
                List<DocumentItem> documents = eFCS.GetDocumentList();

                int documentId = 0;

                string response = "";// "<select id='selectedForm'>";

                foreach (DocumentItem form in documents)
                {
                    documentId = eFCS.GetDocumentId(form.DocumentName, form.DocumentVersion);
                    response += "<option value="+form.DocumentId+">" + form.DocumentName + "</option>";
                }

                //response += " </select>";

                // DropDownListContents.InnerHtml = innerHtml;
                // Request.ContentType = "multipart/form-data";
                context.Response.Write(response);
            }
            catch (Exception)
            {
            }
        }

        public void GetRoleFromSession(HttpContext context)
        {
            string role = Convert.ToString(context.Session["role"]);
            context.Response.Write(role);
        }

    }
}

